package cu.tedu._05weibo.controller;

import cu.tedu._05weibo.common.response.JsonResult;
import cu.tedu._05weibo.common.response.StatusCode;
import cu.tedu._05weibo.mapper.WeiboMapper;
import cu.tedu._05weibo.pojo.dto.WeiboDTO;
import cu.tedu._05weibo.pojo.entity.Weibo;
import cu.tedu._05weibo.pojo.vo.UserVO;
import cu.tedu._05weibo.pojo.vo.WeiboDetailVO;
import cu.tedu._05weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Validated
@Api(tags = "02.微博模块")
@Slf4j
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @ApiOperation(value = "发布微博功能")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession httpSession) {
        UserVO userVO = (UserVO) httpSession.getAttribute("user");
//        if (userVO == null) {//未登录
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        //调用接口
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insertWeibo(weibo);
        //return new JsonResult(StatusCode.OPERATION_SUCCESS);
        return JsonResult.ok();
    }


    @ApiOperation(value = "微博列表功能")
    @GetMapping("selectIndex")
    public JsonResult selectIndex() {
        List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();
        return JsonResult.ok(weiboIndexVOS);
        //return new JsonResult(StatusCode.OPERATION_SUCCESS,weiboIndexVOS);

    }

    @ApiOperation(value = "微博详情页面功能")
    @GetMapping("selectById")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "id", value = "微博编号", required = true, dataType = "int", example = "200"),
                    @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "string")}
    )
    public JsonResult selectById(@Range(min = 200, max = 500, message = "微博编号必须在200-500之间")@RequestParam int id, String username) {

        if (id < 0) {
            throw new IllegalArgumentException("id值无效");
        }
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);
        //return new JsonResult(StatusCode.OPERATION_SUCCESS,weiboDetailVO);
        return JsonResult.ok(weiboDetailVO);
    }
}
